<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template
          slot="menuLeft"
          slot-scope="scope"
        >
          <el-button
            v-if="repair_csdevice_import"
            class="filter-item"
            type="default"
            icon="el-icon-upload2"
            @click="rmImport()"
          >
            导入
          </el-button>
        </template>
        <template
          slot-scope="scope"
          slot="deviceStatusForm"
        >
          <el-select v-model="scope.row.deviceStatus">
            <el-option
              v-for="(item,index) in deviceStatusList"
              :key="index"
              :label='item.label'
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </avue-crud>
    </basic-container>
    <!--导入-->
    <el-dialog
      title="批量导入"
      :visible.sync="uploadlg.show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
    >
      下载模板：<el-button
        type="text"
        size="mini"
        style="color:#409EFF;"
        @click="onDowmload"
      >设备导入模板.xlsx</el-button>

      <br>
      <br>
      <el-upload
        ref="upload"
        class="upload-box"
        drag
        action=""
        :http-request="HttpRequest"
        :auto-upload="false"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        name="files"
        :before-upload="beforeUpload"
        :data="uploadlg.extraData"
        :on-change="changeUpload"
        :on-remove="reMoveUpload"
        :on-success="uploadSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择导入文件</em></div>
      </el-upload>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-upload2"
          @click="submitFile"
        >导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, ImportFile } from '@/api/market/repair/device/csdevice'
import { tableOption } from '@/const/crud/market/repair/device/csdevice'
import { mapGetters } from 'vuex'
import { getDicType, ExportUrlFile } from '@/api/common'
export default {
  name: 'csdevice',
  data () {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      uploadlg: {
        show: false,
        noUploadFile: true
      },
      deviceStatusList: [],
      repair_csdevice_import: false
    }
  },
  mounted () {
    this.repair_csdevice_import = this.permissions.repair_csdevice_import
    getDicType('device_status').then(res => {
      this.deviceStatusList = res.data.data
    })
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permissions.repair_csdevice_add, false),
        delBtn: this.vaildData(this.permissions.repair_csdevice_del, false),
        editBtn: this.vaildData(this.permissions.repair_csdevice_edit, false)
      };
    }
  },
  methods: {
    handleExceed (files) {
      this.$message.warning(`当前导入限制只能上传 1 个文件`)
    },
    // 上传校验
    beforeUpload (file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file
        .type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('导入文件格式只能上传.xlsx或.xls!')
      }

      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.warning('上传文件的大小不能超过 50M!')
      }

      return isLt50M && isExcel
    },
    // 导入成功
    uploadSuccess (response) {
      console.log(response)
      const reSuccess = response.success
      if (reSuccess === 0) {
        if (response.data === null) {
          this.$message({
            type: 'error',
            message: response.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: response.data.map(item => {
              return item.failMsg + '|'
            }).join()
          })
        }
        this.$refs.upload && this.$refs.upload.clearFiles()
        return
      }

      this.uploadlg.show = false
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
      this.$refs.upload.clearFiles()
      this.$refs.listTable.initTableData()
    },
    // 改变上传的文件触发
    changeUpload (file, fileList) {
      if (fileList.length > 0) {
        this.uploadlg.noUploadFile = false
      } else {
        this.uploadlg.noUploadFile = true
      }
    },
    // 删掉上传的文件触发
    reMoveUpload (file, fileList) {
      if (fileList.length === 0) {
        this.uploadlg.noUploadFile = true
      }
    },
    // 手动提交
    submitFile () {
      if (this.uploadlg.noUploadFile) {
        this.$message({
          type: 'warning',
          message: '请选择文件'
        })

        return
      }
      this.$refs.upload.submit()
    },
    //下载文件
    onDowmload () {
      ExportUrlFile('/contract/template/2', {})
    },
    //覆盖请求 
    HttpRequest (file) {
      let formdata = new FormData()
      formdata.append("file", file.file)
      ImportFile(formdata).then(res => {
        if (res.data.code == 0) {
          this.uploadlg.show = false
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
          this.$refs.upload.clearFiles()
          this.getList(this.page)
        } else {
          this.$message({
            type: 'error',
            message: '导入失败!'
          })
        }
      })
    },
    // 导入
    rmImport: function () {
      this.uploadlg.show = true;
    },
    getList (page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    rowDel: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleUpdate: function (row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    handleSave: function (row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange (current) {
      this.page.currentPage = current
    },
    searchChange (form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    }
  }
}
</script>
